package org.example.service;

import org.example.entity.*;
import org.example.mapper.IOrdersMapper;
import org.example.service.OrderDetailetService;
import org.example.dto.OrderDTO;
import org.example.feign.CartFeignClient;
import org.example.feign.BusinessFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersService {

    @Autowired
    private IOrdersMapper ordersMapper;

    @Autowired
    private OrderDetailetService orderDetailetService;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private BusinessFeignClient businessFeignClient;

    // 创建订单
    @Transactional
    public int createOrders(String userId, Integer businessId, Integer daId, Double orderTotal) {
        // 创建订单
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setBusinessId(businessId);
        orders.setDaId(daId);
        orders.setOrderTotal(orderTotal);
        orders.setOrderState(0); // 假设订单初始状态为 0 (未支付)

        // 设置当前日期和时间给 order_date 字段
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        orders.setOrderDate(now.format(formatter)); // 设置 order_date 字段

        // 插入订单记录并获取自动生成的订单ID
        ordersMapper.insert(orders);
        Integer orderId = orders.getOrderId(); // 获取自动生成的订单编号
        System.out.println(orderId);

        // 获取购物车信息（通过 Feign 远程调用）
        List<Cart> cartList = cartFeignClient.listCart(userId, businessId);
        List<OrderDetailet> orderDetailetList = new ArrayList<>();

        for (Cart cart : cartList) {
            // 创建订单明细
            OrderDetailet orderDetailet = new OrderDetailet();
            orderDetailet.setOrderId(orderId); // 使用正确的订单ID
            orderDetailet.setFoodId(cart.getFoodId());
            orderDetailet.setQuantity(cart.getQuantity());
            orderDetailetList.add(orderDetailet); // 加入订单明细列表
        }

        // 批量插入订单明细
        orderDetailetService.saveOrderDetailetList(orderDetailetList);

        // 删除购物车中的相关数据（通过 Feign 远程调用）
        cartFeignClient.removeCart(userId, businessId, null);

        return orderId; // 返回订单编号
    }

    // 根据订单ID获取订单信息，并封装到 OrderDTO
    public OrderDTO getOrdersById(Integer orderId) {
        Orders orders = ordersMapper.selectById(orderId); // 获取订单信息
        // 获取商家信息（通过 Feign 远程调用）
        Business business = businessFeignClient.getBusinessById(orders.getBusinessId());

        // 获取订单明细信息
        List<OrderDetailet> orderDetailetList = orderDetailetService.getOrderDetailetByOrderId(orderId);

        // 创建 OrderDTO 并设置数据
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrders(orders);
        orderDTO.setBusiness(business);
        orderDTO.setOrderDetailets(orderDetailetList);

        return orderDTO;
    }

    // 根据用户ID获取所有订单信息，并封装到 OrderDTO
    public List<OrderDTO> listOrdersByUserId(String userId) {
        List<Orders> ordersList = ordersMapper.selectListByUserId(userId); // 获取用户的所有订单
        List<OrderDTO> orderDTOList = new ArrayList<>();

        for (Orders orders : ordersList) {
            // 获取商家信息（通过 Feign 远程调用）
            Business business = businessFeignClient.getBusinessById(orders.getBusinessId());

            // 获取订单明细信息
            List<OrderDetailet> orderDetailetList = orderDetailetService.getOrderDetailetByOrderId(orders.getOrderId());

            // 创建 OrderDTO 并设置数据
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setOrders(orders);
            orderDTO.setBusiness(business);
            orderDTO.setOrderDetailets(orderDetailetList);

            orderDTOList.add(orderDTO);
        }

        return orderDTOList;
    }
} 